﻿#region

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using CuongHanh.Context;
using CuongHanh.Models;
using CuongHanh.Models.View;
using CuongHanh.Service;
using Ext.Net;

#endregion

namespace CuongHanh.Controllers.FO
{
    public class GemController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DesignAndCustomise(int id)
        {
            string language = GetLanguage();

            List<MyStyle> datas = new List<MyStyle>();

            List<MyStyle> models = MultiCache<MyStyle>.Singleton.GetObjectsByFilter(c => c.StyleTypeId == id && c.ParentId == null).ToList();
            foreach (MyStyle myStyle in models)
            {
                datas.Add(new MyStyle
                          {
                                  Id = myStyle.Id,
                                  Name = language == AppUtil.LANGUAGE_EN
                                          ? myStyle.NameEn
                                          : myStyle.Name,
                                  Code = myStyle.Code
                          });
            }
            ViewBag.Language = GetLanguage();
            ViewBag.StyleType = id;
            return View(models);
        }

        public ActionResult ParentLoadMaterialStoneChildStyle(int styleId)
        {
            string language = GetLanguage();
            MyStyle style = MultiCache<MyStyle>.Singleton.GetCacheByKeyObject(styleId);
            string description = string.Empty;
            if(style != null)
            {
                description = language == AppUtil.LANGUAGE_EN
                        ? style.DescriptionEn
                        : style.Description;
            }

            return Json(new object[]
                        {
                                LoadMaterialByStyleId(styleId,
                                        language),
                                LoadStoneByStyleId(styleId),
                                LoadChildStyles(styleId), description
                        });
        }

        public ActionResult ChildLoadMaterialStone(int styleId)
        {
            string language = GetLanguage();
            return Json(new object[]
                        {
                                LoadMaterialByStyleId(styleId,
                                        language),
                                LoadStoneByStyleId(styleId)
                        });
        }

        private List<MaterialView> LoadMaterialByStyleId(int styleId,
                string language)
        {
            List<MaterialView> datas = new List<MaterialView>();
            IEnumerable<StyleMaterial> modes = CacheList<StyleMaterial>.Singleton.GetCache(styleId).OrderBy(c => c.No);
            foreach (StyleMaterial model in modes)
            {
                Material findModel = CacheContext<Material>.Singleton.GetObject(model.MaterialId);
                if(findModel != null)
                    datas.Add(new MaterialView
                              {
                                      Id = findModel.Id,
                                      Name = language == AppUtil.LANGUAGE_EN
                                              ? findModel.NameEn
                                              : findModel.Name,
                                      Price = model.Price,
                                      PriceOfDifferentSize = model.PriceOfDifferentSize
                              });
            }
            return datas;
        }

        private List<StoneView> LoadStoneByStyleId(int styleId)
        {
            List<StoneView> datas = new List<StoneView>();
            IEnumerable<StyleStone> models = CacheList<StyleStone>.Singleton.GetCache(styleId).OrderBy(c => c.No);
            foreach (StyleStone model in models)
            {
                MyStone findModel = CacheContext<MyStone>.Singleton.GetObject(model.StoneId);
                if(findModel != null)
                    datas.Add(new StoneView
                              {
                                      Id = findModel.Id,
                                      Name = findModel.Name,
                                      ThumnailImage = findModel.Image,
                                      Price = model.Price,
                                      Description = model.Description
                              });
            }
            return datas;
        }

        private List<StyleView> LoadChildStyles(int styleId)
        {
            List<StyleView> datas = new List<StyleView>();
            IEnumerable<MyStyle> models = MultiCache<MyStyle>.Singleton.GetCacheByKeyList(styleId);
            foreach (MyStyle model in models)
            {
                datas.Add(new StyleView
                          {
                                  Id = model.Id,
                                  Name = model.Name,
                                  Image = model.Image
                          });
            }
            return datas;
        }


        public ActionResult GetImage(OrderDetailForGem model, bool isThumnail)
        {
            if (model.ChildStoneId > 0)
                return ChildSelectedStone(model.ParentStyleId,
                        model.ParentMaterialId,
                        model.ChildStyleId,
                        model.ChildMaterialId,
                        model.ChildStoneId,
                        isThumnail);
            if (model.ChildMaterialId > 0)
                return ChildSelectedMaterial(model.ParentStyleId,
                        model.ParentMaterialId,
                        model.ChildStyleId,
                        model.ChildMaterialId,
                        isThumnail);
            if (model.ParentStoneId > 0)
                return SelectedStone(model.ParentStyleId,
                        model.ParentMaterialId,
                        model.ParentStoneId,
                        isThumnail);
            if (model.ParentMaterialId > 0)
                return DrawImage(model.ParentStyleId,
                        model.ParentMaterialId);
            return Content("");
        }

        //[AcceptVerbs(HttpVerbs.Get)]
        //[OutputCache(CacheProfile = "CustomerImages")]
        public ActionResult DrawImage(int styleId,
                int materialId)
        {
            StyleMaterial model = CacheList<StyleMaterial>.Singleton.GetCache(styleId,
                    materialId);
            if(model != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    GetImageBySize1(model.Image,
                            ImageType.Large).Save(ms,
                                    ImageFormat.Jpeg);
                    ms.WriteTo(HttpContext.Response.OutputStream);
                    return File(ms.ToArray(),
                            "image/jpg",
                            string.Format("{0}_{1}_{2}_{3}.jpg",
                                    styleId,
                                    materialId,
                                    0,
                                    0));
                }
            }
            return null;
        }

        public ActionResult SelectedStone(int styleId,
                int materialId,
                int stoneId,
                bool isThumnail)
        {
            StyleMaterial styleMaterial = CacheList<StyleMaterial>.Singleton.GetCache(styleId,
                    materialId);
            StyleStone styleStone = CacheList<StyleStone>.Singleton.GetCache(styleId,
                    stoneId);
            if(styleMaterial != null
               && styleStone != null)
            {
                Bitmap styleImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        styleMaterial.Image)));
                Bitmap stoneImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        styleStone.Image)));

                Bitmap mergeImage = Merge2Image(styleImage,
                        stoneImage,
                        isThumnail);
                //  mergeImage.Save(string.Format("D:\\temp\\{0}.png", DateTime.Now.Ticks), ImageFormat.Jpeg);

                using (MemoryStream ms = new MemoryStream())
                {
                    mergeImage.Save(ms,
                            ImageFormat.Jpeg);
                    return File(ms.ToArray(),
                            "image/jpg",
                            string.Format("{0}_{1}_{2}_{3}.jpg",
                                    styleId,
                                    materialId,
                                    stoneId,
                                    isThumnail.GetHashCode()));
                }
            }
            return null;
        }

        private Bitmap GetBitmap(string path)
        {
            return System.IO.File.Exists(path)
                    ? new Bitmap(path)
                    : null;
        }

        public ActionResult GetImageBySize(string imageName,
                ImageType imageType)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                GetImageBySize1(imageName,
                        imageType).Save(ms,
                                ImageFormat.Jpeg);
                return File(ms.ToArray(),
                        "image/jpg",
                        string.Format("{0}_{1}.jpg",
                                imageName.Substring(0,
                                        imageName.Length - 4),
                                (int) imageType));
            }
        }

        private Bitmap GetImageBySize1(string imageName,
                ImageType imageType)
        {
            int descWidth = 0,
                    descHeight = 0;
            switch (imageType)
            {
                case ImageType.Thumnail:
                    descWidth = 74;
                    descHeight = 74;
                    break;
                case ImageType.Small:
                    descWidth = 300;
                    descHeight = 300;
                    break;
                case ImageType.Large:
                    descWidth = 600;
                    descHeight = 600;
                    break;
            }

            Bitmap mergeImage = new Bitmap(descWidth,
                    descHeight,
                    PixelFormat.Format32bppArgb);

            Graphics graphics = Graphics.FromImage(mergeImage);
            graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear
            graphics.FillRectangle(new SolidBrush(Color.White),
                    0,
                    0,
                    descWidth,
                    descHeight);
            string path = HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                    imageName));
            if(!System.IO.File.Exists(path))
                return mergeImage;
            Bitmap pic1 = new Bitmap(path);
            graphics.DrawImage(pic1,
                    new Rectangle(0,
                            0,
                            descWidth,
                            descHeight),
                    0,
                    0,
                    pic1.Width,
                    pic1.Height,
                    GraphicsUnit.Pixel);
            return mergeImage;
        }

        public ActionResult ChildSelectedMaterial(int parentStyleId,
                int parentMaterialId,
                int childStyleId,
                int childMaterialId,
                bool isThumnail)
        {
            StyleMaterial parentStyleMaterial = CacheList<StyleMaterial>.Singleton.GetCache(parentStyleId,
                    parentMaterialId);
            StyleMaterial childStyleMaterial = CacheList<StyleMaterial>.Singleton.GetCache(childStyleId,
                    childMaterialId);

            if(parentStyleMaterial != null
               && childStyleMaterial != null)
            {
                Bitmap parentImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        parentStyleMaterial.Image)));
                Bitmap childImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        childStyleMaterial.Image)));

                Bitmap mergeImage = Merge2Image(parentImage,
                        childImage,
                        isThumnail);
                //   mergeImage.Save(string.Format("D:\\temp\\{0}.png", DateTime.Now.Ticks), ImageFormat.Jpeg);
                using (MemoryStream ms = new MemoryStream())
                {
                    mergeImage.Save(ms,
                            ImageFormat.Jpeg);
                    return File(ms.ToArray(),
                            "image/jpg",
                            string.Format("{0}_{1}_{2}_{3}_{4}_{5}.jpg",
                                    parentStyleId,
                                    parentMaterialId,
                                    childStyleId,
                                    childMaterialId,
                                    0,
                                    isThumnail.GetHashCode()));
                }
            }
            return null;
        }

        public ActionResult ChildSelectedStone(int parentStyleId,
                int parentMaterialId,
                int childStyleId,
                int childMaterialId,
                int childStoneId,
                bool isThumnail)
        {
            StyleMaterial parentStyleMaterial = CacheList<StyleMaterial>.Singleton.GetCache(parentStyleId,
                    parentMaterialId);
            StyleMaterial childStyleMaterial = CacheList<StyleMaterial>.Singleton.GetCache(childStyleId,
                    childMaterialId);
            StyleStone childStone = CacheList<StyleStone>.Singleton.GetCache(childStyleId,
                    childStoneId);
            if(parentStyleMaterial != null
               && childStyleMaterial != null)
            {
                Bitmap parentImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        parentStyleMaterial.Image)));
                Bitmap childImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        childStyleMaterial.Image)));
                Bitmap childStoneImage = GetBitmap(HttpContext.Server.MapPath(Path.Combine(AppUtil.GEM_IMAGE_PATH,
                        childStone.Image)));

                Bitmap mergeImage = Merge3Image(parentImage,
                        childImage,
                        childStoneImage,
                        isThumnail);

                //       mergeImage.Save(string.Format("D:\\temp\\{0}.png", DateTime.Now.Ticks), ImageFormat.Jpeg);

                using (MemoryStream ms = new MemoryStream())
                {
                    mergeImage.Save(ms,
                            ImageFormat.Jpeg);

                    //image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                    //return File(ms.ToArray(), "image/jpg");
                    return File(ms.ToArray(),
                            "image/jpg",
                            string.Format("{0}_{1}_{2}_{3}_{4}_{5}.jpg",
                                    parentStyleId,
                                    parentMaterialId,
                                    childStyleId,
                                    childMaterialId,
                                    childStone,
                                    isThumnail.GetHashCode()));
                    // ms.WriteTo(HttpContext.Response.OutputStream);
                }
            }
            return null;
        }

     
        public ActionResult StartDesigning()
        {
            return View();
        }

        #region Merge Image
        public Bitmap Merge2Image(Bitmap pic1,
             Bitmap pic2,
             bool isThumnail)
        {
            int descWidth = 600,
                    descHeight = 600;
            if (isThumnail)
            {
                descHeight = 74;
                descWidth = 74;
            }

            Bitmap mergeImage = new Bitmap(descWidth,
                    descHeight,
                    PixelFormat.Format32bppArgb);
            if (pic1 != null
               && pic2 != null)
            {
                int width = Math.Max(pic1.Width,
                        pic2.Width);
                int height = Math.Max(pic1.Height,
                        pic2.Height);

                Graphics graphics = Graphics.FromImage(mergeImage);
                graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear

                graphics.FillRectangle(new SolidBrush(Color.White),
                        0,
                        0,
                        descWidth,
                        descHeight);
                graphics.DrawImage(pic1,
                        new Rectangle(0,
                                0,
                                descWidth,
                                descHeight),
                        0,
                        0,
                        width,
                        height,
                        GraphicsUnit.Pixel);

                graphics.DrawImage(pic2,
                        new Rectangle(0,
                                0,
                                descWidth,
                                descHeight),
                        0,
                        0,
                        width,
                        height,
                        GraphicsUnit.Pixel);
            }
            return mergeImage;
        }

        public Bitmap Merge3Image(Bitmap pic1,
                Bitmap pic2,
                Bitmap pic3,
                bool isThumnail)
        {
            int descWidth = 600,
                    descHeight = 600;
            if (isThumnail)
            {
                descHeight = 74;
                descWidth = 74;
            }
            Bitmap mergeImage = new Bitmap(descWidth,
                    descHeight,
                    PixelFormat.Format32bppArgb);
            if (pic1 != null
               && pic2 != null
               && pic3 != null)
            {
                int width = Math.Max(pic1.Width,
                        pic2.Width);
                int height = Math.Max(pic1.Height,
                        pic2.Height);

                Graphics graphics = Graphics.FromImage(mergeImage);
                graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear

                graphics.FillRectangle(new SolidBrush(Color.White),
                        0,
                        0,
                        descWidth,
                        descHeight);
                graphics.DrawImage(pic1,
                        new Rectangle(0,
                                0,
                                descWidth,
                                descHeight),
                        0,
                        0,
                        width,
                        height,
                        GraphicsUnit.Pixel);

                graphics.DrawImage(pic2,
                        new Rectangle(0,
                                0,
                                descWidth,
                                descHeight),
                        0,
                        0,
                        width,
                        height,
                        GraphicsUnit.Pixel);

                graphics.DrawImage(pic3,
                        new Rectangle(0,
                                0,
                                descWidth,
                                descHeight),
                        0,
                        0,
                        width,
                        height,
                        GraphicsUnit.Pixel);

                //target.Save("C:\\Users\\phuongtran\\Desktop\\filename.png", ImageFormat.Jpeg);
            }
            return mergeImage;
        }

        #endregion

        #region Image

        public ActionResult GetImageFromData(int parentStyleId,
                int parentMaterialId,
                int parentStoneId,
                int childStyleId,
                int childMaterialId,
                int childStoneId,bool isThumnail)
        {
            if(childStoneId > 0)
                return ChildSelectedStone(parentStyleId,
                        parentMaterialId,
                        childStyleId,
                        childMaterialId,
                        childStoneId,
                        isThumnail);
            if(childMaterialId>0)
                return ChildSelectedMaterial(parentStyleId,
                        parentMaterialId,
                        childStyleId,
                        childMaterialId,
                        isThumnail);
            if (parentStoneId > 0)
                return SelectedStone(parentStyleId,
                        parentMaterialId,
                        parentStoneId,
                        isThumnail);
            if (parentMaterialId > 0)
                return DrawImage(parentStyleId,
                        parentMaterialId);
            return Content("");
        }

        #endregion

    }
}
